package com.ninong.ker.admin.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ninong.ker.admin.domain.Dic;
import com.ninong.ker.admin.domain.DicDetail;
import com.ninong.ker.admin.mapper.DicDetailMapper;
import com.ninong.ker.admin.mapper.DicMapper;
import com.ninong.ker.admin.service.DicService;
import com.ninong.ker.admin.service.dto.DicDTO;
import com.ninong.ker.common.exception.CmdException;
import com.ninong.ker.common.tools.Constants;
import com.ninong.ker.common.tools.enums.BusinessEnum;

/**
 * 
 * @author cmd
 *
 */
@Service
public class DicServiceImpl extends ServiceImpl<DicMapper, Dic> implements DicService {
	
	@Autowired
	private DicDetailMapper  dicDetailMapper;

	@Override
	public PageInfo<Dic> listPage(DicDTO dto) {
		PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());
		QueryWrapper<Dic> query = new QueryWrapper<>();
		if (!StringUtils.isEmpty(dto.getCode())) {
			query.like("code", dto.getCode());
		}
		if (!StringUtils.isEmpty(dto.getValue())) {
			query.like("value", dto.getValue());
		}
		List<Dic> lists = baseMapper.selectList(query);
		return new PageInfo<Dic>(lists);
	}

	@Override
	public void delete(String[] ids) {
		List<String> idList = Arrays.asList(ids);
		idList.forEach( id -> {
			Integer count = dicDetailMapper.selectCount(new QueryWrapper<DicDetail>().eq("dic_id", id));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DIC_DETAIL_EXIST);
			}
			
		});
		baseMapper.deleteBatchIds(idList);
	}

	@Override
	public void create(Dic entity) {
		Integer count = null;
		if (StringUtils.isEmpty(entity.getId())) {
			count = baseMapper.selectCount(new QueryWrapper<Dic>().eq("code", entity.getCode()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DIC_CODE_REPEAT);
			}
		} else {
			count = baseMapper
					.selectCount(new QueryWrapper<Dic>().ne("id", entity.getId()).eq("code", entity.getCode()));
			if (count > Constants.ZERO) {
				throw new CmdException(BusinessEnum.DIC_CODE_REPEAT);
			}

		}
		saveOrUpdate(entity);
	}

	@Override
	public Dic get(String id) {
		Dic entity = baseMapper.selectById(id);
		if (ObjectUtils.isEmpty(entity)) {
			entity = new Dic();
		}
		return entity;
	}

}
